package com.longcai.piaojia.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.conn.Conn;
import com.longcai.piaojia.conn.GetBalanceGet;
import com.longcai.piaojia.conn.OrderExpiredGet;
import com.longcai.piaojia.conn.WalletPayPost;
import com.longcai.piaojia.fragment.FragmentTicketOrder;
import com.longcai.piaojia.fragment.MineFragment;
import com.longcai.piaojia.util.ClickUtil;
import com.longcai.piaojia.util.MyToast;
import com.longcai.piaojia.util.WxPay;
import com.module.zfb.PayAction;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;

import java.math.BigDecimal;

/**
 * Created by Administrator on 2016/8/2.
 */
public class PayActivity extends BaseActivity implements View.OnClickListener {

    public static final String PAY_RECEIVER = "payBroadcastReceiver";
    public static final String PAY_FINISH_RECEIVER = "payBroadcastFinishReceiver";

    @BoundView(R.id.title_back_rl) private RelativeLayout title_back_rl;

    @BoundView(R.id.pay_type_ll) private LinearLayout pay_type_ll;
    @BoundView(R.id.pay_price_tv) private TextView pay_price_tv;

    @BoundView(R.id.pay_price_check_tv) private TextView pay_price_check_tv;
    @BoundView(R.id.pay_price_check_rl) private RelativeLayout pay_price_check_rl;
    @BoundView(R.id.pay_price_check_sel_iv) private ImageView pay_price_check_sel_iv;
    @BoundView(R.id.pay_price_check_no_iv) private ImageView pay_price_check_no_iv;

    @BoundView(R.id.pay_wechat_rl) private RelativeLayout pay_wechat_rl;
    @BoundView(R.id.pay_wechat_check_sel_iv) private ImageView pay_wechat_check_sel_iv;
    @BoundView(R.id.pay_wechat_check_no_iv) private ImageView pay_wechat_check_no_iv;
    @BoundView(R.id.pay_alipay_rl) private RelativeLayout pay_alipay_rl;
    @BoundView(R.id.pay_alipay_check_sel_iv) private ImageView pay_alipay_check_sel_iv;
    @BoundView(R.id.pay_alipay_check_no_iv) private ImageView pay_alipay_check_no_iv;
    @BoundView(R.id.activity_pay_price_tv) private TextView activity_pay_price_tv;
    @BoundView(R.id.pay_submit_bt) private TextView pay_submit_bt;

    private int payType = 0;
    private String orderNum;
    private String allPrice;
    private String truePrice;
    private String title;
    private String classid;
    private String orderId;
    private String orderNo;
    private String ordertotalAmount;
    private String postage; //邮费
    private boolean isOrder = false;
    private GetBalanceGet.BalanceEntity balance;
    private String walletPrice = "0.00", privilegePrice = "0.00";

    private OrderExpiredGet orderExpiredGet = new OrderExpiredGet(new AsyCallBack<String>(){

        @Override
        public void onSuccess(String toast, int type, String s) throws Exception {

            switch (payType) {

                case 0:

                    WxPay wxPay = new WxPay(PayActivity.this);

//                    Log.e("---------", "privilege" + privilegePrice + "wallet" + walletPrice + "truePrice" + String.valueOf(Float.parseFloat(truePrice) * 100).replace(".0", ""));
//                    wxPay.pay(title, orderNum, "1", "1,"+BaseApplication.BasePreferences.readUserId()+","+privilegePrice+","+walletPrice+","+orderId+","+orderNo+","+ordertotalAmount);
                    wxPay.pay(title, orderNum, String.valueOf(Float.parseFloat(truePrice) * 100).replace(".0", ""), "1," + BaseApplication.BasePreferences.readUserId() + "," + privilegePrice + "," + walletPrice + "," + orderId + "," + orderNo + "," + ordertotalAmount);

                    break;

                case 1:

                    PayAction payAction = new PayAction(PayActivity.this) {
                        @Override
                        protected void onSuccess() {

                            payEnd();

                        }

                        @Override
                        protected void onEnd() {

                            payFinish();

                        }
                    };

                    try {

//                        Log.e("---------", "privilege" + privilegePrice + "wallet" + walletPrice + "truePrice" + truePrice);
//                        payAction.pay(title, BaseApplication.BasePreferences.readUserId() + "," + privilegePrice + "," + walletPrice + "," + orderId + "," + orderNo + "," + ordertotalAmount, orderNum, "0.01", Conn.SERVICE + Conn.ALIPAY_NOTIFYURL);
                        payAction.pay(title, BaseApplication.BasePreferences.readUserId()+","+privilegePrice+","+walletPrice+","+orderId+","+orderNo+","+ordertotalAmount, orderNum, truePrice, Conn.SERVICE + Conn.ALIPAY_NOTIFYURL);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    WalletPayPost.user_id = BaseApplication.BasePreferences.readUserId();
                    WalletPayPost.out_trade_no = orderNum;
                    WalletPayPost.privilege = privilegePrice;
                    WalletPayPost.wallet = walletPrice;
                    WalletPayPost.orderId = orderId;
                    WalletPayPost.orderNo = orderNo;
                    WalletPayPost.trilateralMoney = ordertotalAmount;
                    WalletPayPost.execute(PayActivity.this);

                    break;

            }



        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.show(context, toast, MyToast.LENGTH_SHORT);

            pay_submit_bt.setEnabled(true);

        }
    });

    private GetBalanceGet getBalanceGet = new GetBalanceGet(new AsyCallBack<GetBalanceGet.BalanceEntity>(){

        @Override
        public void onSuccess(String toast, int type, GetBalanceGet.BalanceEntity balanceEntity) throws Exception {
            super.onSuccess(toast, type, balanceEntity);

            balance = balanceEntity;

            BigDecimal privilege;

            if(BaseApplication.BasePreferences.readIsFavourable().equals("2") && getIntent().getExtras().getString("is_balance").equals("1")){ //&& classid.equals("6")

                privilege = new BigDecimal(balanceEntity.privilege);

            }else{

                privilege = new BigDecimal("0.00");
                balanceEntity.privilege = "0.00";// 我加的


            }

            BigDecimal wallet = new BigDecimal(balanceEntity.wallet);

//            BigDecimal privilege_result = privilege.subtract(new BigDecimal(truePrice));
            BigDecimal wallet_result = wallet.subtract(new BigDecimal(postage));

            BigDecimal price = privilege.add(wallet);

            if(Float.parseFloat(truePrice) < Float.parseFloat(postage) && Float.parseFloat(postage) > Float.parseFloat(new BigDecimal(allPrice).subtract(privilege).toString())){

                payType = 0;

                pay_type_ll.setVisibility(View.VISIBLE);

                balanceEntity.privilege = "0.00";// 我加的

                pay_price_tv.setText("-" + getResources().getString(R.string.money_icon_text) + balanceEntity.wallet + getResources().getString(R.string.goods_info_money_text));

                truePrice = new BigDecimal(allPrice).subtract(wallet).toString();

                walletPrice = balance.wallet;
                privilegePrice = balance.privilege;

            }else{

                if(Float.parseFloat(allPrice)>Float.parseFloat(price.toString())){

//                pay_price_tv.setText("-"+getResources().getString(R.string.money_icon_text)+price.toString()+getResources().getString(R.string.goods_info_money_text));

                    pay_type_ll.setVisibility(View.VISIBLE);

                    pay_price_tv.setVisibility(View.GONE);

                    pay_price_check_tv.setVisibility(View.VISIBLE);

                    pay_price_check_rl.setVisibility(View.VISIBLE);

                    pay_price_check_tv.setText("-"+getResources().getString(R.string.money_icon_text)+"0.00"+getResources().getString(R.string.goods_info_money_text));

                    truePrice = allPrice;

                    if(BaseApplication.BasePreferences.readIsFavourable().equals("2") && getIntent().getExtras().getString("is_balance").equals("1")){

                        if(Float.parseFloat(new BigDecimal(allPrice).subtract(privilege).toString()) < Float.parseFloat(postage)){

//                            truePrice = new BigDecimal(allPrice).subtract(privilege).add(new BigDecimal(postage)).toString();

                            balanceEntity.privilege = privilege.subtract(new BigDecimal(postage)).toString();

                        }

                    }

                }else{

                    payType = 2;

                    pay_type_ll.setVisibility(View.GONE);

                    if(BaseApplication.BasePreferences.readIsFavourable().equals("2") && getIntent().getExtras().getString("is_balance").equals("1")){ //&& classid.equals("6")

                        BigDecimal result = privilege.subtract(new BigDecimal(truePrice));

                        if(result.signum() == -1){

                            balanceEntity.wallet = new BigDecimal(allPrice).subtract(privilege).toString();

                            pay_price_tv.setText("-" + getResources().getString(R.string.money_icon_text) + allPrice + getResources().getString(R.string.goods_info_money_text));

                            walletPrice = balance.wallet;
                            privilegePrice = balance.privilege;

                        }else {

                            balanceEntity.privilege = truePrice;

                            if(wallet_result.signum() == -1){

                                payType = 0;

                                pay_type_ll.setVisibility(View.VISIBLE);

                                pay_price_tv.setText("-" + getResources().getString(R.string.money_icon_text) + new BigDecimal(allPrice).subtract(new BigDecimal(postage).subtract(wallet)) + getResources().getString(R.string.goods_info_money_text));

                                truePrice = new BigDecimal(postage).subtract(wallet).toString();

                                walletPrice = balance.wallet;
                                privilegePrice = balance.privilege;

                            }else{

                                balanceEntity.wallet = postage;

                                pay_price_tv.setText("-" + getResources().getString(R.string.money_icon_text) + allPrice + getResources().getString(R.string.goods_info_money_text));

                                walletPrice = balance.wallet;
                                privilegePrice = balance.privilege;

                            }

                        }

                    }else{

                        balanceEntity.privilege = "0.00";// 我加的
                        balanceEntity.wallet = allPrice;

                        pay_price_tv.setText("-" + getResources().getString(R.string.money_icon_text) + allPrice + getResources().getString(R.string.goods_info_money_text));

                        walletPrice = balance.wallet;
                        privilegePrice = balance.privilege;

                    }

                    pay_price_tv.setVisibility(View.VISIBLE);

                    pay_price_check_tv.setVisibility(View.GONE);

                    pay_price_check_rl.setVisibility(View.GONE);


                }

            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            Toast.makeText(PayActivity.this, toast, Toast.LENGTH_LONG).show();

        }
    });

    private WalletPayPost WalletPayPost = new WalletPayPost(new AsyCallBack<String>(){

        @Override
        public void onSuccess(String toast, int type, String s) throws Exception {
            super.onSuccess(toast, type, s);

            payEnd();

            Toast.makeText(PayActivity.this, toast, Toast.LENGTH_LONG).show();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {
            super.onFail(toast, type);

            payFinish();

            Toast.makeText(PayActivity.this, toast, Toast.LENGTH_LONG).show();

        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pay);

        title_back_rl.setVisibility(View.VISIBLE);

        setTitleName(getResources().getString(R.string.pay_title_text));

        orderNum = getIntent().getExtras().getString("orderNum", "");
        allPrice = getIntent().getExtras().getString("truePrice", "");
        title = getIntent().getExtras().getString("title", "");
        isOrder = getIntent().getExtras().getBoolean("isOrder", false);
        classid = getIntent().getExtras().getString("classid", "");
        orderId = getIntent().getExtras().getString("orderId", "");
        orderNo = getIntent().getExtras().getString("orderNo", "");
        ordertotalAmount = getIntent().getExtras().getString("ordertotalAmount", "");
        postage = getIntent().getExtras().getString("postage", "0");
        truePrice = new BigDecimal(allPrice).subtract(new BigDecimal(postage)).toString();

        activity_pay_price_tv.setText(allPrice);

        title_back_rl.setOnClickListener(this);
        pay_wechat_rl.setOnClickListener(this);
        pay_alipay_rl.setOnClickListener(this);
        pay_price_check_rl.setOnClickListener(this);
        pay_submit_bt.setOnClickListener(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PAY_RECEIVER);
        intentFilter.addAction(PAY_FINISH_RECEIVER);

        registerReceiver(payBroadCast, intentFilter);

        getBalanceGet.user_id = BaseApplication.BasePreferences.readUserId();
        getBalanceGet.type_id = classid;
        getBalanceGet.execute(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.title_back_rl:

                payFinish();

                break;

            case R.id.pay_price_check_rl:

                if (pay_price_check_sel_iv.getVisibility() == View.INVISIBLE) {

                    walletPrice = balance.wallet;
                    privilegePrice = balance.privilege;

                    BigDecimal privilege = new BigDecimal(balance.privilege);

                    BigDecimal wallet = new BigDecimal(balance.wallet);

                    BigDecimal price = privilege.add(wallet);

                    BigDecimal allprice = new BigDecimal(allPrice);

                    truePrice = allprice.subtract(price).toString();

                    pay_price_check_sel_iv.setVisibility(View.VISIBLE);
                    pay_price_check_no_iv.setVisibility(View.INVISIBLE);

                    pay_price_check_tv.setText("-" + getResources().getString(R.string.money_icon_text) + price.toString() + getResources().getString(R.string.goods_info_money_text));

                } else {

                    walletPrice = "0.00";
                    privilegePrice = "0.00";

                    BigDecimal privilege = new BigDecimal(balance.privilege);

                    BigDecimal wallet = new BigDecimal(balance.wallet);

                    BigDecimal price = privilege.add(wallet);

                    BigDecimal allprice = new BigDecimal(truePrice);

                    truePrice = allprice.add(price).toString();

                    pay_price_check_sel_iv.setVisibility(View.INVISIBLE);
                    pay_price_check_no_iv.setVisibility(View.VISIBLE);

                    pay_price_check_tv.setText("-" + getResources().getString(R.string.money_icon_text) + "0.00" + getResources().getString(R.string.goods_info_money_text));

                }

                break;

            case R.id.pay_wechat_rl:

                pay_wechat_check_sel_iv.setVisibility(View.VISIBLE);
                pay_alipay_check_no_iv.setVisibility(View.VISIBLE);

                pay_wechat_check_no_iv.setVisibility(View.GONE);
                pay_alipay_check_sel_iv.setVisibility(View.GONE);

                payType = 0;

                break;

            case R.id.pay_alipay_rl:

                pay_alipay_check_sel_iv.setVisibility(View.VISIBLE);
                pay_wechat_check_no_iv.setVisibility(View.VISIBLE);

                pay_alipay_check_no_iv.setVisibility(View.GONE);
                pay_wechat_check_sel_iv.setVisibility(View.GONE);

                payType = 1;

                break;

            case R.id.pay_submit_bt:

                Log.e("---------", "privilege" + privilegePrice + "wallet" + walletPrice + "truePrice" + String.valueOf(Float.parseFloat(truePrice) * 100).replace(".0", "") + "payType:" + payType);

//                if (ClickUtil.isFastClick()) {
//                    return ;
//                }
                pay_submit_bt.setEnabled(false);

                orderExpiredGet.order = orderNum;
                orderExpiredGet.execute(this);

                break;

        }

    }

    private void payFinish(){

        Intent intent = new Intent(PayActivity.this, MyOrderDetailActivity.class);
        intent.putExtra("order_number", orderNum);
        intent.putExtra("isPayed", false);
        startActivity(intent);

        finish();

    }

    private void payEnd(){

        if(isOrder){

            try {

                MyOrderDetailActivity.RefreshDetail refreshDetail = (MyOrderDetailActivity.RefreshDetail) getAppCallBack(MyOrderDetailActivity.class);
                refreshDetail.refresh();

                finish();

                FragmentTicketOrder.RefreshOrderList refreshOrderList = (FragmentTicketOrder.RefreshOrderList) getAppCallBack(FragmentTicketOrder.class);
                refreshOrderList.refresh();

                MineFragment.getUserAdvert getUserAdvert = (MineFragment.getUserAdvert) getAppCallBack(MineFragment.class);
                getUserAdvert.refreshInfo();


            } catch (Exception e) {
                e.printStackTrace();
            }

        }else{

            Intent intent = new Intent(PayActivity.this, MyOrderDetailActivity.class);
            intent.putExtra("order_number", orderNum);
            intent.putExtra("isPayed", true);
            startActivity(intent);

            finish();

        }

//        if(isOrder){
//
//            try {
//
////                FragmentTicketOrder.RefreshOrderList refreshOrderList = (FragmentTicketOrder.RefreshOrderList) getAppCallBack(FragmentTicketOrder.class);
////                refreshOrderList.refresh();
//
//                MyOrderDetailActivity.RefreshDetail refreshDetail = (MyOrderDetailActivity.RefreshDetail) getAppCallBack(MyOrderDetailActivity.class);
//                refreshDetail.refresh();
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//
//        }else{
//
//            try {
//
//                MyOrderDetailActivity.RefreshDetail refreshDetail = (MyOrderDetailActivity.RefreshDetail) getAppCallBack(MyOrderDetailActivity.class);
//                refreshDetail.refresh();
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        }
//        else{
//
//            BaseApplication.INSTANCE.finishActivity(GoodsInfoActivity.class, ChooseGoodsActivity.class, SubmitOrderActivity.class);
//
//            startActivity(new Intent(PayActivity.this, MyOrderListActivity.class));
//
//            Intent intent = new Intent(PayActivity.this, MyOrderDetailActivity.class);
//
//            intent.putExtra("order_number", orderNum);
//
//            startActivity(intent);
//
//        }

    }

    public BroadcastReceiver payBroadCast = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(PAY_RECEIVER)){

                payEnd();

            } else if(intent.getAction().equals(PAY_FINISH_RECEIVER)){

                payFinish();

            }

        }

    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            payFinish();

            return false;
        }


        return super.onKeyDown(keyCode, event);
    }
}
